
_ = require('lodash')
require 'umeditor/umeditor.config'
require 'umeditor/umeditor'
#require 'jquery.atwho'

class Editor
  #constructor: (el, height="220", width='auto', triangleClass=null) ->
  constructor: (el, style={}, toolbar) ->
    return null if _.isEmpty?($("##{el}"))
    window.instanceCache = window.instanceCache || {}
    width = style['width'] || 'auto'
    height = style['height'] || '220'
    try
      if $('#global-hidden-is-mobile').text() == 'true'
        height = '60'
    catch error
      "ignore..."
    triangleClass = style['triangleClass']
    isAutoHeightEnabled = if style['autoHeightEnabled'] == undefined then true else style['autoHeightEnabled']
    pasteImageEnabled = if style['pasteImageEnabled'] == true then true else false

    ue = @makeInstance(el, width, height, triangleClass, isAutoHeightEnabled, pasteImageEnabled, toolbar)
    # do it for multi instance
    this.umeditor = ue
    this.umeditorId = el

    if (not _.isEmpty(window.instanceCache)) && window.instanceCache[this.umeditor.uid]
      delete window.instanceCache[this.umeditor.uid]
      this.umeditor.destroy()
      this.umeditor = @makeInstance(el, width, height, triangleClass, isAutoHeightEnabled, pasteImageEnabled, toolbar)

    window.instanceCache[this.umeditor.uid] = true
    return this

  clearSelf: () ->
    this.umeditor.setContent("")
    this.umeditor.blur()

  makeInstance: (el, width, height, triangleClass, isAutoHeightEnabled, pasteImageEnabled, toolbar) ->
    return UM.getEditor el, {
            initialFrameWidth: width
            initialFrameHeight: height
            triangleClass: triangleClass
            autoHeightEnabled: isAutoHeightEnabled
            pasteImageEnabled: pasteImageEnabled
            #filterRules: @filterRulesFun()
            zIndex: 220
            toolbar: toolbar
           }


  doListen: (customEvent=null, users=[], stocks=[]) ->
    self = this
    #console.log users
    this.umeditor.addListener 'ready', () ->
      if customEvent
        customEvent.call(this, self.umeditor)
     # $(".edui-body-container").atwho
        #at: "$"
        #startWithSpace: false
        #insertTpl: '$${name}&nbsp;'
        #searchKey: 'name'
        #callbacks:
          #remoteFilter: (query, callback) ->
            #$.ajax(
              #"/search/at_stock"
              #data: {q: query}
              #dataType: 'json'
              #global: false
              #success: (data) ->
                          #a = _.map(data, (item) ->
                                      #name:
                                        #"#{item['compShortName']}(#{item['compCode']})"
                                   #)
                          #callback(a)
            #)
        #limit: 7
        #displayTpl : "<li data-value='${name}'>${name}</li>"
    this.umeditor.fireEvent('ready')
      #.atwho
        #at: "@"
        #startWithSpace: false
        #insertTpl: '@${nickname} '
        #displayTpl : "<li data-value='${nickname}'>${nickname}</li>"
        #searchKey: 'nickname'
        #limit: 7
        #data: users
        #
        #

  editorContentsCheck: (umeditor, wordCountLimit=null, atUserText='') ->
    wordCountLimitFlag = true
    plainTxt = umeditor.getPlainTxt()
    if wordCountLimit != null
      wordCountLimitFlag = (plainTxt.replace(/\s/g,'').length <= wordCountLimit)
    return {flag: false, message: 'wordCountLimit' } unless wordCountLimitFlag
    return {flag: umeditor.hasRealContents() and (plainTxt.replace(/\s/g,'') != atUserText.replace(/\s/g, '')), message: null}

  filterRulesFun: () ->

    return {
      span: (node) ->
        if /Wingdings|Symbol/.test(node.getStyle("font-family"))
          true
        else
          node.parentNode.removeChild node, true
      #$:{}表示不保留任何属性
      br:
        $: {}
      ol:
        $: {}

      ul:
        $: {}

      dl: (node) ->
        node.tagName = "ul"
        node.setAttr()

      dt: (node) ->
        node.tagName = "li"
        node.setAttr()

      dd: (node) ->
        node.tagName = "li"
        node.setAttr()

      li: (node) ->
        className = node.getAttr("class")
        node.setAttr()  if not className or not /list\-/.test(className)
        tmpNodes = node.getNodesByTagName("ol ul")
        UM.utils.each tmpNodes, (n) ->
          node.parentNode.insertAfter n, node


      table: (node) ->
        UM.utils.each node.getNodesByTagName("table"), (t) ->
          UM.utils.each t.getNodesByTagName("tr"), (tr) ->
            p = UM.uNode.createElement("p")
            child = undefined
            html = []
            while child = tr.firstChild()
              html.push child.innerHTML()
              tr.removeChild child
            p.innerHTML html.join("&nbsp;&nbsp;")
            t.parentNode.insertBefore p, t

          t.parentNode.removeChild t

        val = node.getAttr("width")
        node.setAttr()
        node.setAttr "width", val  if val

      tbody:
        $: {}

      caption:
        $: {}

      th:
        $: {}

      td:
        $:
          valign: 1
          align: 1
          rowspan: 1
          colspan: 1
          width: 1
          height: 1

      tr:
        $: {}

      h3:
        $: {}

      h2:
        $: {}


      #黑名单，以下标签及其子节点都会被过滤掉
      "-": "script style meta iframe embed object"
    }

module.exports = (el, style={}, toolbar=['forecolor', 'bold', 'italic', 'underline', 'image', 'video', 'justifyleft', 'justifycenter', 'justifyright']) ->
  new Editor(el, style, toolbar)

